package cn.daniellee.plugin.rs.storage;

import cn.daniellee.plugin.rs.RestrictedShop;
import cn.daniellee.plugin.rs.model.PlayerData;
import com.google.gson.Gson;

import java.sql.*;

public class SqliteStorage extends Storage {

	private Connection connection;

	@Override
	public boolean initialize() {
		// 初始化Sqlite驱动
		try {
			Class.forName("org.sqlite.JDBC");
		} catch (ClassNotFoundException e) {
			RestrictedShop.getInstance().getLogger().info(" ");
			RestrictedShop.getInstance().getLogger().info("[RestrictedShop]An error occurred while getting the Sqlite database driver.".replace("&", "§"));
			RestrictedShop.getInstance().getLogger().info(" ");
			e.printStackTrace();
			return false;
		}
		// 初始化连接
		String url = "jdbc:sqlite:" + RestrictedShop.getInstance().getDataFolder() + "/" + "storage.db";
		try {
			connection = DriverManager.getConnection(url);
		} catch (Exception e) {
			RestrictedShop.getInstance().getLogger().info(" ");
			RestrictedShop.getInstance().getLogger().info("[RestrictedShop]Sqlite connection information is incorrect.".replace("&", "§"));
			RestrictedShop.getInstance().getLogger().info(" ");
			e.printStackTrace();
			return false;
		}
		// 初始化数据表
		String sql = "CREATE TABLE IF NOT EXISTS `player` (" +
				"`name` TEXT(48) NOT NULL," +
				"`shop` TEXT(32) NOT NULL," +
				"`check_sum` TEXT(32) NOT NULL," +
				"`index_list` TEXT(255)," +
				"`purchase_numbers` TEXT(255)," +
				"`sold_numbers` TEXT(255)," +
				"`percentage` INTEGER(5)," +
				"`generate_at` INTEGER(20)" +
				");";
		String indexSql = "CREATE UNIQUE INDEX IF NOT EXISTS `index_player` ON `player` (`name`, `shop`);";
		try (Statement statement = connection.createStatement()) {
			statement.execute(sql);
			statement.execute(indexSql);
		} catch (SQLException e) {
			RestrictedShop.getInstance().getLogger().info(" ");
			RestrictedShop.getInstance().getLogger().info("[RestrictedShop]An error occurred while initializing the Mysql data table.".replace("&", "§"));
			RestrictedShop.getInstance().getLogger().info(" ");
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public Connection getConnection() {
		return connection;
	}

	@Override
	public PlayerData getPlayerData(String name, String shop) {
		String sql = " SELECT `name`,`shop`,`check_sum`,`index_list`,`purchase_numbers`,`sold_numbers`,`percentage`,`generate_at` FROM `player` WHERE `name` = ? AND `shop` = ?";
		try (PreparedStatement statement = connection.prepareStatement(sql)) {
			statement.setString(1, name);
			statement.setString(2, shop);
			ResultSet resultSet = statement.executeQuery();
			if (resultSet.next()) {
				PlayerData playerData = new PlayerData();
				playerData.setName(resultSet.getString("name"));
				playerData.setShop(resultSet.getString("shop"));
				playerData.setCheckSum(resultSet.getString("check_sum"));
				playerData.setIndexList(new Gson().fromJson(resultSet.getString("index_list"), Integer[].class));
				playerData.setPurchaseNumbers(new Gson().fromJson(resultSet.getString("purchase_numbers"), Integer[].class));
				playerData.setSoldNumbers(new Gson().fromJson(resultSet.getString("sold_numbers"), Integer[].class));
				playerData.setPercentage(resultSet.getInt("percentage"));
				playerData.setGenerateAt(resultSet.getLong("generate_at"));
				return playerData;
			}
		} catch (SQLException e) {
			RestrictedShop.getInstance().getLogger().info(" ");
			RestrictedShop.getInstance().getLogger().info("[RestrictedShop]An error occurred while reading building data from Mysql.".replace("&", "§"));
			RestrictedShop.getInstance().getLogger().info(" ");
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void savePlayerData(PlayerData playerData) {
		String sql = "INSERT OR REPLACE INTO `player` (`name`,`shop`,`check_sum`,`index_list`,`purchase_numbers`,`sold_numbers`,`percentage`,`generate_at`) VALUES (?,?,?,?,?,?,?,?);";
		try (PreparedStatement statement = connection.prepareStatement(sql)) {
			statement.setString(1, playerData.getName());
			statement.setString(2, playerData.getShop());
			statement.setString(3, playerData.getCheckSum());
			String indexList = new Gson().toJson(playerData.getIndexList());
			statement.setString(4, indexList);
			String purchaseNumbers = new Gson().toJson(playerData.getPurchaseNumbers());
			statement.setString(5, purchaseNumbers);
			String soldNumbers = new Gson().toJson(playerData.getSoldNumbers());
			statement.setString(6, soldNumbers);
			statement.setInt(7, playerData.getPercentage());
			statement.setLong(8, playerData.getGenerateAt());
			statement.executeUpdate();
		} catch (SQLException e) {
			RestrictedShop.getInstance().getLogger().info(" ");
			RestrictedShop.getInstance().getLogger().info("[RestrictedShop]An error occurred while reading building data from Mysql.".replace("&", "§"));
			RestrictedShop.getInstance().getLogger().info(" ");
			e.printStackTrace();
		}
	}

	@Override
	public void deletePlayerData(String name, String shop) {
		String sql = "DELETE FROM `player` WHERE `name` = ? AND `shop` = ?;";
		try (PreparedStatement statement = connection.prepareStatement(sql)) {
			statement.setString(1, name);
			statement.setString(2, shop);
			statement.execute();
		} catch (SQLException e) {
			RestrictedShop.getInstance().getLogger().info(" ");
			RestrictedShop.getInstance().getLogger().info("[RestrictedShop]An error occurred while reading building data from Mysql.".replace("&", "§"));
			RestrictedShop.getInstance().getLogger().info(" ");
			e.printStackTrace();
		}
	}

	@Override
	public void close() {
		try {
			connection.close();
		} catch (SQLException ignored) { }
	}
}
